<template>
  <div>
    <el-form label-width="auto">
      <el-form-item label="SKU名称">
        <el-input placeholder="请输入SKU名称" type="text" v-model="skuParams.skuName" />
      </el-form-item>
      <el-form-item label="SKU价格">
        <el-input placeholder="价格(元)" type="number" v-model="skuParams.price" />
      </el-form-item>
      <el-form-item label="SKU重量">
        <el-input placeholder="重量(克)" type="number" v-model="skuParams.weight" />
      </el-form-item>
      <el-form-item label="SKU描述">
        <el-input placeholder="SKU描述" type="textarea" v-model="skuParams.skuDesc" />
      </el-form-item>
      <!-- 通过遍历每个数据的数组,渲染出多个框,再在多个框中使用for遍历数组内的数组,实现多选框.在属性值中,使用v-model在每一个数组中动态创建一个值存储多选框选中的值 -->
      <el-form-item label="SKU属性">
        <ElForm :inline="true">
          <ElFormItem
            v-for="(item, index) in attrArr"
            :key="item.id"
            :label="item.attrName"
            label-width="80px"
          >
            <el-select placeholder="请选择" style="width: 30vh" v-model="item.attrIDAndValueID">
              <el-option
                :value="`${item.id}:${saleAttrValue.id}`"
                v-for="(saleAttrValue, index) in item.attrValueList"
                :key="saleAttrValue.id"
                :label="saleAttrValue.valueName"
              ></el-option>
            </el-select>
          </ElFormItem>
        </ElForm>
      </el-form-item>
      <el-form-item label="SKU销售属性">
        <ElForm :inline="true">
          <ElFormItem
            v-for="(item, index) in spuSaleArr"
            :key="item.id"
            :label="item.saleAttrName"
            label-width="50px"
          >
            <el-select placeholder="请选择" style="width: 30vh" v-model="item.saleIDAndValueId">
              <el-option
                v-for="(spuSaleAttrValue, index) in item.spuSaleAttrValueList"
                :key="spuSaleAttrValue.id"
                :label="spuSaleAttrValue.saleAttrValueName"
                :value="`${item.id}:${spuSaleAttrValue.id}`"
              ></el-option>
            </el-select>
          </ElFormItem>
        </ElForm>
      </el-form-item>
      <el-form-item label="SKU图片">
        <el-table
          ref="table"
          type
          style="width: 100%; width: 100%; margin: 10px 0px"
          border
          :data="spuImageListArr"
          select-on-indeterminate
        >
          <el-table-column label="序号" width="80px" align="center" type="selection" />
          <el-table-column label="图片" align="">
            <template #="{ row, $index }">
              <ElImage style="width: 100px; height: 100px" :fit="fit" :src="row.imgUrl"></ElImage>
            </template>
          </el-table-column>
          <el-table-column label="名称" align="" prop="imgName"> </el-table-column>
          <el-table-column label="操作" align="">
            <template #="{ row, $index }">
              <el-button
                type="primary"
                size="small"
                title="设置为默认浏览的图片"
                @click="handler(row)"
                >设置默认</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" title="保存" @click="save">保存</el-button>
        <el-button type="primary" title="取消" @click="cancal">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup name="SKUFROM">
import { reqAttr } from '@/API/product/attr'
import { Attr, AttrData } from '@/API/product/attr/type'
import { reqAddSku, reqHasExistingSpuSaleAttrList, reqHasSpuImageList } from '@/API/product/spu'
import { SpuRecordData, ImageList, SaleAttrData, SkuData } from '@/API/product/spu/type'
import useSpuStore from '@/store/modules/useSpu'
import { clear } from 'console'
import { ElImage } from 'element-plus'
import { onMounted, ref } from 'vue'

let SpuStore = useSpuStore()
/* 收集平台属性的与销售属性的属性和其属性值,*/
let attrArr = ref<AttrData>([])
let spuSaleArr = ref<SaleAttrData>([])
let spuImageListArr = ref<ImageList>([])
let table = ref()
let skuParams = ref<SkuData>({
  /* 收集添加所需要的参数 */
  //父组件中的c3id三级分类id,已有SPU的ID,品牌的ID(category3Id,spuId,tmId)
  //本页面需要的sku名称,价格,重量,描述,sku平台属性,sku的销售属性,sku的图片(skuName price weight skuDesc skuAttrValueList skuSaleAttrValueList  skuDefaultImg)
  category3Id: '',
  price: '',
  spuId: '',
  tmId: '',
  skuDefaultImg: '',
  skuName: '',
  weight: '',
  skuDesc: '',
  skuAttrValueList: [],
  skuSaleAttrValueList: []
})

let $emit = defineEmits(['changUpDataHasSpu'])
const cancal = () => {
  clearSkuParam()
  $emit('changUpDataHasSpu', { store: 'add' })
  SpuStore.scene = 0
}
const getSkuData = async (c1ID: number | string, c2ID: number | string, spu: SpuRecordData) => {
  skuParams.value.category3Id = spu.category3Id
  skuParams.value.spuId = spu.id
  skuParams.value.tmId = spu.tmId
  /* 获取品牌的属性和其属性值数据数组 */
  let result = await reqAttr(c1ID, c2ID, spu.category3Id)
  // spu.id是品牌的id
  /* 获取SPU属性的数据数组和图片的数据数组 */
  let result1 = await reqHasExistingSpuSaleAttrList(spu.id)
  let result2 = await reqHasSpuImageList(spu.id)
  attrArr.value = result.data
  spuSaleArr.value = result1.data
  spuImageListArr.value = result2.data
  console.log(spu)
}
/* 设置默认,获取该图片 */
const handler = (row) => {
  console.log(table.value)
  /* element的table组件方法,清空多选框 */
  table.value.clearSelection()
  /* toggleRowSelection方法传两个值,一个是当前被点击的实例对象,一个是布尔值,决定选中还是取消选中 */
  table.value.toggleRowSelection(row, true)
  skuParams.value.skuDefaultImg = row.imgUrl
}
const save = async () => {
  // 先整理数据,将其数据整理成我们上传需要的相应变量名
  /* 
    使用数组的reduce方法
          先给予prev的默认值为一个数组
          next等于遍历数组的值
          再在每次执行中判断是否有attrIDAndValueID这个值,如果有,我们使用字符串的方法spilt将其除去制定字符,并让其分割为字符串前后的两个数组
          再进行解构赋值.
          后给我们的prev数组push添加赋值后的对象.
          最后为attrArr中的attrIDAndValueID字符串分出冒号后的两个字符串的数组
          
  */
  skuParams.value.skuAttrValueList = attrArr.value.reduce((prev, next) => {
    if (next.attrIDAndValueID) {
      let [attrIdStr, valueIdStr] = next.attrIDAndValueID.split(':')
      let attrId = Number(attrIdStr)
      let valueId = Number(valueIdStr)
      prev.push({
        attrId,
        valueId
      })
      /* 如果写在if循环内,会导致我们没有值的循环判断后不返回值,从而导致出现prev是Undefined的情况.然后报错,一定要有返回值! */
      // return prev
    }
    return prev
  }, [])
  skuParams.value.skuSaleAttrValueList = spuSaleArr.value.reduce((prev, next) => {
    if (next.saleIDAndValueId) {
      let [saleAttrIdStr, saleAttrValueIdStr] = next.saleIDAndValueId.split(':')
      let saleAttrId = Number(saleAttrIdStr)
      let saleAttrValueId = Number(saleAttrValueIdStr)
      prev.push({
        saleAttrId,
        saleAttrValueId
      })
      /* 如果写在if循环内,会导致我们没有值的循环判断后不返回值,从而导致出现prev是Undefined的情况.然后报错,一定要有返回值! */
      // return prev
    }
    return prev
  }, [])
  let result = await reqAddSku(skuParams.value)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '添加SKU成功'
    })
    clearSkuParam()
    $emit('changUpDataHasSpu', { store: 'updata' })
    SpuStore.scene = 0
  } else {
    ElMessage({
      type: 'error',
      message: '添加SKU失败'
    })
  }
}
const clearSkuParam = () => {
  skuParams.value = {
    category3Id: '',
    price: '',
    spuId: '',
    tmId: '',
    skuDefaultImg: '',
    skuName: '',
    weight: '',
    skuDesc: '',
    skuAttrValueList: [],
    skuSaleAttrValueList: []
  }
}
onMounted(() => {})
defineExpose({ getSkuData })
</script>

<style scoped></style>
